<?php

namespace app\common\model;

use think\Model;

/**
 * 会员积分日志模型
 */
class ScoreLog Extends Model
{

    // 表名
    protected $name = 'user_score_log';
    // 开启自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';
    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = '';
    // 追加属性
    protected $append = [
    ];


    /**
     * 积分记录分页列表
     *
     * @param string $mold 类型:all=全部,earning=收入,expend=支出
     * @param string $start_time 开始时间
     * @param string $end_time 结束时间
     * @param int $page 页码
     * @param int $limit 每页数据
     */
    public function getPageList($params,$user_id,$page = 1,$limit = 10)
    {
        extract($params);

        try {
            $where = [
                'user_id' => $user_id
            ];
            $start_time = empty($start_time)?strtotime(datetime(time(),'Y-m-1')):strtotime($start_time);
            $end_time = empty($end_time)?strtotime('+1 day'):strtotime('+1 day',strtotime($end_time));
            $where['createtime'] = ['between',[$start_time,$end_time]];
            switch ($mold){
                case 'all':
                    break;
                case 'earning':
                    $where['score'] = ['>', 0];
                    break;
                case 'expend':
                    $where['score'] = ['<', 0];
                    break;
            }

            $field = ['id', 'user_id', 'score', 'memo', 'createtime'];
            $list = $this
                ->with(['user' => function($query){
                    $query->field('id,nickname');
                }])
                ->field($field)
                ->where($where)
                ->order('createtime', 'desc')
                ->paginate($limit, false, ['page' => $page]);

            foreach ($list as $row) {
                $row->createtime = datetime($row->createtime);
//                if(!$row->user){
//                    $row->user = ['nickname' => '管理员'];
//                }
            }

            return [
                'code' => 200,
                'msg' => '请求成功',
                'data' => $list
            ];
        }catch (\Exception $e) {
            return [
                'code' => $e->getCode(),
                'msg' => $e->getMessage(),
                'data' => $e->getLine()
            ];
        }
    }




    public function user(){
        return $this->belongsTo('app\common\model\User','user_id','id');
    }

}
